<template>
  <el-card>
    <div class="toolbar">
      <el-button type="primary" @click="onAdd">新增标签</el-button>
    </div>
    <el-table :data="tagList" border stripe style="margin-top: 16px;">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="标签名称" width="120" />
      <el-table-column prop="type" label="标签类型" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.type === '自动' ? 'success' : 'info'">{{ scope.row.type }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="color" label="标签颜色" width="100">
        <template #default="scope">
          <el-tag :color="scope.row.color" disable-transitions class="tag-white-text">{{ scope.row.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="desc" label="描述" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === '启用' ? 'success' : 'info'">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="80" />
      <el-table-column prop="memberCount" label="会员数量" width="100">
        <template #default="scope">
          <el-link type="primary" @click="onShowMembers(scope.row)">{{ scope.row.memberCount || 0 }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button size="small" @click="onEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="onDelete(scope.row)">删除</el-button>
          <el-button size="small" @click="onToggleStatus(scope.row)">{{ scope.row.status === '启用' ? '停用' : '启用' }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="showForm" :title="form.id ? '编辑标签' : '新增标签'" width="700px">
      <el-form :model="form" label-width="90px" :rules="rules" ref="formRef">
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="标签类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="自动">自动</el-radio>
            <el-radio label="手动">手动</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标签颜色" prop="color">
          <el-color-picker v-model="form.color" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="form.desc" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="1" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="启用">启用</el-radio>
            <el-radio label="停用">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="form.type === '自动'" class="rule-section-title">规则配置</div>
        <el-form v-if="form.type === '自动'" label-width="110px">
            <el-form-item label="购物频率">
              <el-input-number v-model="form.ruleOrderCount" :min="0" placeholder="订单数" style="width:120px;" />
              <span style="margin:0 8px;">单 / 近</span>
              <el-input-number v-model="form.ruleOrderPeriodNum" :min="1" placeholder="周期数" style="width:120px;" />
              <el-select v-model="form.ruleOrderPeriodUnit" placeholder="周期单位" style="width:80px;">
                <el-option label="天" value="天" />
                <el-option label="月" value="月" />
                <el-option label="年" value="年" />
              </el-select>
            </el-form-item>
            <el-form-item label="客单价区间">
              <el-input-number v-model="form.ruleMinOrderPrice" :min="0" placeholder="最低" style="width:120px;" />
              <span style="margin:0 8px;">-</span>
              <el-input-number v-model="form.ruleMaxOrderPrice" :min="0" placeholder="最高" style="width:120px;" />
              <span style="margin-left:8px;">日元</span>
            </el-form-item>
            <el-form-item label="累计消费金额">
              <el-input-number v-model="form.ruleTotalAmount" :min="0" placeholder="金额" style="width:120px;" />
              <span style="margin-left:8px;">日元</span>
              <span style="margin-left:16px;">近</span>
              <el-input-number v-model="form.ruleTotalAmountPeriodNum" :min="1" placeholder="周期数" style="width:120px;" />
              <el-select v-model="form.ruleTotalAmountPeriodUnit" placeholder="周期单位" style="width:80px;">
                <el-option label="天" value="天" />
                <el-option label="月" value="月" />
                <el-option label="年" value="年" />
              </el-select>
            </el-form-item>
            <el-form-item label="品类偏好">
              <el-select v-model="form.ruleCategories" multiple placeholder="请选择品类" style="width:240px;">
                <el-option v-for="cat in categoryOptions" :key="cat" :label="cat" :value="cat" />
              </el-select>
              <el-input-number v-model="form.ruleCategoryRatio" :min="0" :max="100" placeholder="占比" style="width:120px; margin-left:8px;" />
              <span style="margin-left:4px;">%</span>
            </el-form-item>
            <el-form-item label="地域特征">
              <el-select v-model="form.ruleRegions" multiple placeholder="请选择地区" style="width:240px;">
                <el-option v-for="region in regionOptions" :key="region" :label="region" :value="region" />
              </el-select>
            </el-form-item>
            <el-form-item label="生命周期">
              <el-select v-model="form.ruleLifecycle" placeholder="请选择节点" style="width:180px;">
                <el-option label="新客" value="新客" />
                <el-option label="活跃用户" value="活跃用户" />
                <el-option label="沉默风险" value="沉默风险" />
                <el-option label="流失用户" value="流失用户" />
                <el-option label="忠诚用户" value="忠诚用户" />
              </el-select>
            </el-form-item>
            <el-form-item label="特殊行为">
              <el-input v-model="form.ruleSpecial" placeholder="如：参与过2024春季活动" />
            </el-form-item>
            <el-form-item label="自定义表达式">
              <el-input v-model="form.ruleCustom" placeholder="如：order_count>=5 AND region='东京'" />
            </el-form-item>
          </el-form>
          <el-alert v-if="form.rule" :title="form.rule" type="info" show-icon class="rule-preview" />
        <el-form-item v-if="form.type === '手动'" label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="如：客服备注、活动说明等" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showForm = false">取消</el-button>
        <el-button type="primary" @click="onSave">保存</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="showMemberDialog" title="标签下会员列表" width="400px">
      <el-table :data="currentMembers" size="small" border>
        <el-table-column prop="nickname" label="昵称" width="120" />
        <el-table-column prop="id" label="会员ID" width="100" />
        <el-table-column prop="phone" label="手机号" />
      </el-table>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const tagList = ref([
  { id: 1, name: '高客单用户', type: '自动', color: '#f56c6c', desc: '近30天消费≥50万日元', status: '启用', sort: 1, rule: 'order_amount>=500000', remark: '', memberCount: 2, members: [ { id: 1001, nickname: '用户A', phone: '138****0001' }, { id: 1002, nickname: '用户B', phone: '139****0002' } ] },
  { id: 2, name: 'VIP客户', type: '手动', color: '#67c23a', desc: '重要KOL/大代理商', status: '启用', sort: 2, rule: '', remark: '社长推荐', memberCount: 1, members: [ { id: 1003, nickname: '用户C', phone: '137****0003' } ] },
  { id: 3, name: '药妆达人', type: '自动', color: '#409eff', desc: '美妆个护类消费占比≥70%', status: '启用', sort: 3, rule: 'beauty_ratio>=0.7', remark: '', memberCount: 0, members: [] },
  { id: 4, name: '纠纷风险', type: '手动', color: '#e6a23c', desc: '有过恶意投诉记录', status: '停用', sort: 4, rule: '', remark: '需主管审核', memberCount: 1, members: [ { id: 1004, nickname: '用户D', phone: '136****0004' } ] }
]);

const showForm = ref(false);
const formRef = ref();
const categoryOptions = [
  '美妆个护', '母婴用品', '食品饮料', '数码家电', '服饰鞋包', '动漫周边', '保健品', '家居生活'
];
const regionOptions = [
  '东京', '神奈川', '北海道', '大阪', '名古屋', '福冈', '冲绳', '京都'
];
const form = reactive({
  id: undefined,
  name: '',
  type: '自动',
  color: '#409eff',
  desc: '',
  status: '启用',
  sort: 1,
  rule: '',
  ruleOrderCount: undefined,
  ruleOrderPeriodNum: undefined,
  ruleOrderPeriodUnit: '月',
  ruleMinOrderPrice: undefined,
  ruleMaxOrderPrice: undefined,
  ruleTotalAmount: undefined,
  ruleTotalAmountPeriodNum: undefined,
  ruleTotalAmountPeriodUnit: '月',
  ruleCategories: [],
  ruleCategoryRatio: undefined,
  ruleRegions: [],
  ruleLifecycle: '',
  ruleSpecial: '',
  ruleCustom: '',
  ruleOther: '',
  remark: ''
});
const rules = {
  name: [{ required: true, message: '请输入标签名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择标签类型', trigger: 'change' }],
  color: [{ required: true, message: '请选择标签颜色', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
};

const showMemberDialog = ref(false);
const currentMembers = ref([]);
function onShowMembers(row: any) {
  currentMembers.value = row.members || [];
  showMemberDialog.value = true;
}

function onAdd() {
  Object.assign(form, { id: undefined, name: '', type: '自动', color: '#409eff', desc: '', status: '启用', sort: 1, rule: '',
    ruleOrderCount: undefined, ruleOrderPeriodNum: undefined, ruleOrderPeriodUnit: '月',
    ruleMinOrderPrice: undefined, ruleMaxOrderPrice: undefined,
    ruleTotalAmount: undefined, ruleTotalAmountPeriodNum: undefined, ruleTotalAmountPeriodUnit: '月',
    ruleCategories: [], ruleCategoryRatio: undefined, ruleRegions: [], ruleLifecycle: '', ruleSpecial: '', ruleCustom: '', ruleOther: '', remark: '' });
  showForm.value = true;
}
function onEdit(row: any) {
  Object.assign(form, JSON.parse(JSON.stringify(row)));
  showForm.value = true;
}
function onDelete(row: any) {
  ElMessageBox.confirm('确定要删除该标签吗？', '提示', { type: 'warning' }).then(() => {
    tagList.value = tagList.value.filter(t => t.id !== row.id);
    ElMessage.success('删除成功');
  });
}
function onToggleStatus(row: any) {
  row.status = row.status === '启用' ? '停用' : '启用';
  ElMessage.success('操作成功');
}
function onSave() {
  formRef.value.validate((valid: boolean) => {
    if (!valid) return;
    // 自动标签规则描述拼接
    if (form.type === '自动') {
      let ruleDesc = [];
      if (form.ruleOrderCount) ruleDesc.push(`购物频率：${form.ruleOrderCount}单/${form.ruleOrderPeriodNum}${form.ruleOrderPeriodUnit}`);
      if (form.ruleMinOrderPrice || form.ruleMaxOrderPrice) ruleDesc.push(`客单价：${form.ruleMinOrderPrice || 0}-${form.ruleMaxOrderPrice || '不限'}日元`);
      if (form.ruleTotalAmount) ruleDesc.push(`消费金额：${form.ruleTotalAmount}日元`);
      if (form.ruleOther) ruleDesc.push(form.ruleOther);
      form.rule = ruleDesc.join('，');
    }
    if (form.id) {
      // 编辑
      const idx = tagList.value.findIndex(t => t.id === form.id);
      if (idx > -1) tagList.value[idx] = JSON.parse(JSON.stringify(form));
      ElMessage.success('编辑成功');
    } else {
      // 新增
      form.id = Date.now();
      tagList.value.push(JSON.parse(JSON.stringify(form)));
      ElMessage.success('新增成功');
    }
    showForm.value = false;
  });
}
</script>

<style scoped>
.toolbar {
  margin-bottom: 16px;
  display: flex;
  gap: 12px;
}
.rule-section-title {
  font-weight: bold;
  font-size: 15px;
  margin: 12px 0 8px 0;
}
.rule-preview {
  margin-top: 12px;
}
/* 会员标签颜色列白色文字 */
.tag-white-text {
  color: #fff !important;
}
</style> 